#include "source.h"
#include "gps.h"

int parse_comma_delimited_str(char *string, char **fields, int max_fields) {
  int i = 0;
  fields[i++] = string;

  while (i < max_fields && (string = strchr(string, ','))) {
    *string = '\0';
    fields[i++] = ++string;
  }

  return --i;
}

int nmea_sentence_to_time(char *sentence, struct GpsTime *time) {
  char *field[20];
  int token_count = parse_comma_delimited_str(sentence, field, 20);

  if (token_count == 12 && strcmp(field[0], "$GPRMC") == 0) {
    char hour[3], min[3], sec[3];
    strncpy(hour, &field[1][0], 2);
    strncpy(min, &field[1][2], 2);
    strncpy(sec, &field[1][4], 2);
    hour[2] = '\0';
    min[2] = '\0';
    sec[2] = '\0';

    time->hour = atoi(hour);
    time->minute = atoi(min);
    time->second = atoi(sec);

    return 1;
  }
  return 0;
}
